package com.druid;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.druid.conf.SourceDBConfig;
import com.druid.conf.TargetDBConfig;
import com.druid.data.source.SourceUser;
import com.druid.data.target.TargetUser;
import com.druid.data.target.TargetUserExample;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 合服user表脚本
 */
@Service
public class MergeService {

    @Autowired
    private SourceService sourceService;
    @Autowired
    private TargetService targetService;
    @Autowired
    private SourceDBConfig sourceDBConfig;
    @Autowired
    private TargetDBConfig targetDBConfig;

    public static Logger MERGE_LOG = LoggerFactory.getLogger("MERGE");

    public void merge(int pageMax) {
        /**
         * 测试 获取user表dump
         * mysqldump --opt --single-transaction --set-gtid-purged=OFF -t orm -h 127.0.0.1 -P 3306 -u root -proot --tables user >./1_user.sql
         */
        final int pageLimit = pageMax;//每次处理多少条
        final long sourceTotalSize = sourceService.getSourceUserMapper().countByExample(null);
        final long totalPage = sourceTotalSize % pageLimit == 0 ? sourceTotalSize / pageLimit : sourceTotalSize / pageLimit + 1;
        MERGE_LOG.info("合并地址：" + sourceDBConfig.url);
        MERGE_LOG.info("目标地址：" + targetDBConfig.url);
        MERGE_LOG.info("开始合并user表!!! 总数：{} 每页：{} 页数：{}", sourceTotalSize, pageLimit, totalPage);
        long insertCount = 0;
        long mergeCount = 0;
        long start = System.currentTimeMillis();
        for (int i = 1; i <= totalPage; i++) {
            long pageStart = System.currentTimeMillis();
            long pageInsertCount = 0;
            long pageMergeCount = 0;
            PageHelper.startPage(i, pageLimit);
            PageInfo<SourceUser> result = new PageInfo<>(sourceService.getSourceUserMapper().selectByExample(null));
            if (result.getList().isEmpty()) {
                break;
            }
            for (SourceUser sourceUser : result.getList()) {
                TargetUserExample example = new TargetUserExample();
                example.createCriteria().andKEqualTo(sourceUser.getK());
                List<TargetUser> targetUserList = targetService.getTargetUserMapper().selectByExample(example);
                if (targetUserList.isEmpty()) {
                    //直接插入target库
                    TargetUser insertTarget = new TargetUser();
                    insertTarget.setK(sourceUser.getK());
                    insertTarget.setV(sourceUser.getV());
                    targetService.getTargetUserMapper().insert(insertTarget);
                    insertCount++;
                    pageInsertCount++;
                } else {
                    //合并user表idList
                    TargetUser targetUser = targetUserList.get(0);
                    JSONObject targetObject = JSON.parseObject(targetUser.getV());
                    String targetIdListStr = targetObject.getString("2");
                    ArrayList targetIdList = JSON.parseObject(targetIdListStr, ArrayList.class);
                    long targetCreateTime = targetObject.getLongValue("3");
                    int targetUserINitFlag = targetObject.getIntValue("4");

                    JSONObject sourceObject = JSON.parseObject(sourceUser.getV());
                    String sourceIdListStr = sourceObject.getString("2");
                    ArrayList sourceIdList = JSON.parseObject(sourceIdListStr, ArrayList.class);
                    long sourceCreateTime = sourceObject.getLongValue("3");
                    int sourceUserINitFlag = sourceObject.getIntValue("4");

                    //合并
                    if (targetCreateTime > sourceCreateTime || targetCreateTime == 0L) {
                        targetObject.put("3", sourceCreateTime);
                    }
                    if (sourceUserINitFlag > targetUserINitFlag) {
                        targetObject.put("4", sourceUserINitFlag);
                    }
                    ArrayList mergedIdList = new ArrayList();
                    mergedIdList.addAll(targetIdList);
                    mergedIdList.addAll(sourceIdList);
                    targetObject.put("2", mergedIdList);
                    targetUser.setV(JSON.toJSONString(targetObject));

                    targetService.getTargetUserMapper().updateByPrimaryKeySelective(targetUser);
                    mergeCount++;
                    pageMergeCount++;
                }
            }
            long pageEnd = System.currentTimeMillis();
            MERGE_LOG.info("完成合并user表第{}页 总数：{} 插入：{}条 合并：{}条 耗时：{}秒", i, result.getList().size(), pageInsertCount, pageMergeCount, (pageEnd - pageStart) / 1000);
        }
        long end = System.currentTimeMillis();
        MERGE_LOG.info("完成合并user表  总数：{} 插入：{}条 合并：{}条 耗时：{}秒", sourceTotalSize, insertCount, mergeCount, (end - start) / 1000);
    }
}
